<template>
  <div id="phone-upload" v-show="$store.state.theme">
    <div style="margin:auto;width: 50%;" v-if="showprogress">
      <div class="upload-progress" style="display: inline-block;">
        <div class="progress-w" :style="`width:${progress}%`"></div>
      </div>
      <div style="display: inline-block;margin-left: 10px">{{progress|init}}%</div>
    </div>
    <div v-show="imageList" class="select">
      <div class="select-icon" @click="handleclick">
        <p class="select-icon-item"></p>
        <p>从相册中选择图片</p>
      </div>
      <div class="select-image">
        <span @click="handleclick">选择图片</span>
      </div>
      <input
        ref="phoneUpload"
        multiple
        accept="image/*"
        style="display: none"
        type="file"
        @change="phoneUpload"
      >
    </div>
    <div class="upload-list" v-show="!imageList">
      <div class="upload-list-item" v-for="(item, i) in list" :key="i">
        <img :src="item" alt="">
      </div>
      <div class="upload-btn" @click="handleclick">
        <span>继续上传</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  head() {
    return {
      script: [{ src: "/js/wx.js", type: "text/javascript", charset: "utf-8" }]
    };
  },
  data() {
    return {
      TeamNum: null,
      type: null,
      param: null,
      imageList: true,
      list: [],
      showprogress: false,
      progress: 0, // 上传进度
      timer: null,
      dep: 0,
      weixinJSSDK: false // 微信的jsdk是否可用
    };
  },
  filters: {
    init(val) {
      return val.toFixed(2);
    }
  },
  mounted() {
    this.$setTheme(this.$store);
    this.createInfo();
    this.getwx();
  },
  methods: {
    createInfo() {
      let query = this.$route.query;
      // console.log(query)
      let type = query.type;
      this.type = type
      this.TeamNum = query.teamNum;
      this.param =
        type == "true"
          ? {
              uuid: query.uuid || "",
              TypeNum: 0,
              TypeCategoryNum: 0,
              KeyWords: "",
              IsPublic: 0
            }
          : {
              uuid: query.uuid || "",
              TeamNum: this.TeamNum || "",
              TypeNum: 0,
              TypeCategoryNum: 0,
              IsPublic: 0
            };
    },
    // 点击激活上传
    handleclick() {
      var ua = window.navigator.userAgent.toLowerCase();
      //判断是不是微信
      var weixin = ua.match(/MicroMessenger/i) == "micromessenger";
      var android = ua.match(/Android/i) == "android";
      if (weixin && android) {
        if (this.weixinJSSDK) {
          this.androidUpload();
        } else {
          alert("配置微信公众号JS接口安全域名");
        }
      } else {
        this.$refs.phoneUpload.click();
      }
    },
    //上传事件被激活
    phoneUpload() {
      this.imageList = false;
      let phoneUpload = this.$refs.phoneUpload;
      var files = phoneUpload.files;
      this.dep = files.length;
      var uploadList = [];
      for (var i = 0; i < files.length; i++) {
        let formdata = new FormData();
        for (let key in this.param) {
          formdata.append(key, this.param[key]);
        }
        formdata.append("file", files[i]);
        uploadList.push(formdata);
        this.imgtolist(files[i]);
      }
      this.showprogress = true;
      this.progress = 0;
      this.$message.closeAll();
      Promise.all(
        Array.from(uploadList).map((file, index) => {
          return new Promise(resolve => {
            this.handleUploadBtn(file).then(data => {
              this.progress += 100 / this.dep;
              resolve(data);
            });
          });
        })
      ).then(arr => {
        this.showprogress = false;
        this.$message({
          message: "上传成功! ",
          duration: 0,
          type: "success",
          customClass: "info",
          showClose: true
        });
      });
    },
    // 上传图片到服务器
    handleUploadBtn(formdata) {
      return new Promise(resolve => {
        console.log(this.type, 'type的')
        let url = this.type == "true" ? this.$store.state.port.DesignerMaterial : this.$store.state.port.TeamMaterial;
        this.$axios
          .post(url, formdata)
          .then(({ data }) => {
            data = typeof data == "object" ? data : JSON.parse(data);
            resolve(data);
          })
          .catch(err => {
            this.$message({
              message: "上传失败! ",
              duration: 0,
              type: "error",
              customClass: "info",
              showClose: true
            });
          });
      });
    },
    getwx() {
      // 配置微信小程序可使用api的权限
      var formdata = new FormData();
      formdata.append("url", location.href.split("#")[0]);
      this.$axios.post("/wxjssdksign", formdata).then(({ data }) => {
        var config = data.result;

        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: config.appId, // 必填，公众号的唯一标识
          timestamp: Number(config.timestamp), // 必填，生成签名的时间戳
          nonceStr: config.nonceStr, // 必填，生成签名的随机串
          signature: config.signature, // 必填，签名
          jsApiList: ["chooseImage", "checkJsApi", "getLocalImgData"] // 必填，需要使用的JS接口列表
        });

        wx.ready(() => {
          this.weixinJSSDK = true;
          console.log("配置成功", this.weixinJSSDK);
        });
        wx.error(function(res) {
          console.log(res, "配置出错");
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });
      });
    },

    //显示上传的图片
    imgtolist(file) {
      let reader = new FileReader();
      //将文件以Data URL形式读入页面
      reader.onload = () => {
        this.list.push(reader.result);
      };
      reader.readAsDataURL(file);
    },

    //安卓微信浏览器里面选择照片
    androidUpload() {
      var that = this;
      this.imageList = false;
      wx.chooseImage({
        count: 20,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success(res) {
          if (res.errMsg == "chooseImage:ok") {
            // tempFilePath可以作为img标签的src属性显示图片
            var localIds = res.localIds;
            Promise.all(
              Array.from(localIds).map((localId, i) => {
                return new Promise(resolve => {
                  that.getLocalImg(localIds[i]).then(form => {
                    resolve(form);
                  });
                });
              })
            ).then(uploadList => {
              console.log(uploadList, "微信选择");
              that.showprogress = true;
              that.progress = 0;
              that.$message.closeAll();
              var dep = uploadList.length;
              Promise.all(
                Array.from(uploadList).map((file, index) => {
                  return new Promise(resolve => {
                    that.handleUploadBtn(file).then(data => {
                      that.progress += 100 / dep;
                      resolve(data);
                    });
                  });
                })
              ).then(arr => {
                that.showprogress = false;
                that.$message({
                  message: "上传成功! ",
                  duration: 0,
                  type: "success",
                  customClass: "info",
                  showClose: true
                });
              });
            });
          }
        }
      });
    },

    getLocalImg(localId) {
      return new Promise(resolve => {
        if (!localId) return resolve("");
        var that = this;
        wx.getLocalImgData({
          localId: localId, //图片本地地址
          success: res => {
            const localData = res.localData;
            let imageBase64 = "";
            if (localData.indexOf("data:image") == 0) {
              //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
              imageBase64 = localData;
            } else {
              //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
              //此时一个正常的base64图片路径就完美生成赋值到img的src中了
              imageBase64 =
                "data:image/png;base64," + localData.replace(/\n/g, "");
            }
            resolve(that.dataURLtoBlob(imageBase64));
          }
        });
      });
    },

    dataURLtoBlob(dataurl) {
      // base64转blob
      this.list.push(dataurl);
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      let formdata = new FormData();
      for (let key in this.param) {
        formdata.append(key, this.param[key]);
      }
      formdata.append("file", new Blob([u8arr], { type: mime }));
      return formdata;
      //  new Blob([u8arr], { type: mime });
    }
  }
};
</script>

<style scoped lang="less">
#phone-upload {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 99;
  overflow-y: scroll;
  .select {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    height: 100%;
    text-align: center;
    .select-icon {
      font-size: 14px;
      text-align: center;
      .select-icon-item {
        width: 50px;
        height: 50px;
        margin: 0 auto;
        border-radius: 50%;
        background: linear-gradient(to right, #4facfe, #00f2f1);
      }
    }
    .select-image {
      margin-top: 30px;
      span {
        display: inline-block;
        padding: 5px 20px;
        background: linear-gradient(to right, #4facfe, #00f2f1);
        border-radius: 20px;
        color: #fff;
        font-size: 14px;
      }
    }
  }
  .upload-list {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    .upload-list-item {
      width: 26%;
      height: 100px;
      overflow: hidden;
      margin: 10px;
      img {
        display: block;
        height: 100%;
      }
    }
    .upload-btn {
      position: absolute;
      left: 40%;
      bottom: -60px;
      span {
        display: inline-block;
        padding: 5px 20px;
        background: linear-gradient(to right, #4facfe, #00f2f1);
        border-radius: 20px;
        color: #fff;
        font-size: 14px;
      }
    }
  }
  .upload-progress {
    margin: auto;
    width: 60%;
    height: 10px;
    background-color: #c5eafe;
    overflow: hidden;
    border-radius: 5px;
    .progress-w {
      height: 100%;
      border-radius: 5px;
      background-color: #745bff;
      transition: width ease 0.4s;
    }
  }
}
</style>
